package org.ehe.erp.controller.quality;

import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.monitor.MonitorMethod;
import org.ehe.business.overdue.extract.FeedBackDataExtractor;
import org.ehe.business.overdue.extract.ProjectDataExtractor;
import org.ehe.business.overdue.extract.PurcharOrderDataExtractor;
import org.ehe.business.overdue.extract.QualityDataExtractor;
import org.ehe.business.project.domain.ProjectEntity;
import org.ehe.business.timeout.contants.BizTypeConstant;
import org.ehe.common.core.BaseController;
import org.ehe.common.core.domain.R;
import org.ehe.common.core.validate.AddGroup;
import org.ehe.common.core.validate.EditGroup;
import org.ehe.common.idempotent.annotation.RepeatSubmit;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.erp.domain.purchase.ErpPurchaseOrder;
import org.ehe.erp.domain.purchase.vo.ErpPurchaseOrderItemVo;
import org.ehe.erp.domain.quality.ErpQualityTask;
import org.ehe.erp.domain.quality.bo.ErpQualityTaskBo;
import org.ehe.erp.domain.quality.dto.QualityTaskQueryDto;
import org.ehe.erp.domain.quality.vo.ErpQualityTaskVo;
import org.ehe.erp.service.quality.ErpQualityTaskService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 质检任务控制器
 *
 * @author zhangnn
 * @className ErpQualityTaskController
 * @description 质检任务管理控制器
 * @date 2025-09-11 15:00:00
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/quality/task")
public class ErpQualityTaskController extends BaseController {

    private final ErpQualityTaskService qualityTaskService;

    /**
     * 查询质检任务列表（分页）
     */
    @SaCheckPermission("quality:task:list")
    @GetMapping("/list")
    public TableDataInfo<ErpQualityTaskVo> list(QualityTaskQueryDto queryDto, PageQuery pageQuery) {
        return qualityTaskService.queryPageList(queryDto, pageQuery);
    }


    /**
     * 获取质检项目
     * @return
     */
    @SaCheckPermission("quality:task:query")
    @GetMapping("/queryQualityItems/{taskId}")
    public TableDataInfo<ErpPurchaseOrderItemVo> queryQualityItems(@PathVariable Long taskId) {
        return qualityTaskService.queryQualityItems(taskId);
    }


    /**
     * 查询质检任务列表（不分页）
     */
    @SaCheckPermission("quality:task:list")
    @GetMapping("/listAll")
    public R<List<ErpQualityTaskVo>> listAll(QualityTaskQueryDto queryDto) {
        List<ErpQualityTaskVo> list = qualityTaskService.queryList(queryDto);
        return R.ok(list);
    }

    /**
     * 获取质检任务详细信息
     */
    @SaCheckPermission("quality:task:query")
    @GetMapping("/{id}")
    public R<ErpQualityTaskVo> getInfo(@PathVariable Long id) {
        ErpQualityTaskVo vo = qualityTaskService.queryById(id);
        return R.ok(vo);
    }

    /**
     * 新增质检任务
     */
    @MonitorMethod(bizType = BizTypeConstant.QUALITY+"Overdue", extractor = QualityDataExtractor.class)
    @SaCheckPermission("quality:task:add")
    @Log(title = "新增质检任务", linkType = "quality", businessType = BusinessType.INSERT, idField = "id", nameField = "taskNo")
    @PostMapping
    public R<ErpQualityTask> add(@Validated(AddGroup.class) @RequestBody ErpQualityTaskBo bo) {
        return R.ok("新增质检任务成功",qualityTaskService.insertByBo(bo));
    }

    /**
     * 修改质检任务
     */
    //@MonitorMethod(bizType = BizTypeConstant.QUALITY+"Overdue", extractor = FeedBackDataExtractor.class)
    @SaCheckPermission("quality:task:edit")
    @Log(title = "修改质检任务", linkType = "quality", businessType = BusinessType.UPDATE, idField = "id", nameField = "taskNo")
    @PutMapping
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ErpQualityTaskBo bo) {
        return toAjax(qualityTaskService.updateByBo(bo));
    }

    /**
     * 删除质检任务
     */
    @SaCheckPermission("quality:task:remove")
    @Log(title = "删除质检任务", linkType = "quality", businessType = BusinessType.DELETE, idField = "id", nameField = "id")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@PathVariable Long[] ids) {
        return toAjax(qualityTaskService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 分配质检任务给指定人员
     */
    @MonitorMethod(bizType = BizTypeConstant.QUALITY+"Overdue", extractor = QualityDataExtractor.class)
    @SaCheckPermission("quality:task:assign")
    @Log(title = "分配质检任务给指定人员", linkType = "quality", businessType = BusinessType.UPDATE, idField = "id", nameField = "assignUserName")
    @PutMapping("/assign")
    public R<ErpQualityTask> assignTask(@RequestParam Long taskId,
                              @RequestParam Long assignUserId,
                              @RequestParam String assignUserName) {
        return R.ok("分配人员成功",qualityTaskService.assignTask(taskId, assignUserId, assignUserName));
    }


    /**
     * 提交质检任务
     * @param id
     * @return
     */
    @SaCheckPermission("quality:task:submit")
    @MonitorMethod(bizType = BizTypeConstant.QUALITY+"Overdue", extractor = QualityDataExtractor.class)
    @Log(title = "提交质检任务", linkType = "purchaseOrder", businessType = BusinessType.UPDATE, nameField = "orderName")
    @RepeatSubmit()
    @PostMapping("/respondOrder/{id}/{days}")
    public R<ErpQualityTask> respondOrder(@PathVariable("id") Long id,@PathVariable Integer days) {
        return R.ok(qualityTaskService.respondOrder(id,days));
    }

    /**
     * 开始质检
     */
    @SaCheckPermission("quality:task:start")
    @Log(title = "开始质检", linkType = "quality", businessType = BusinessType.UPDATE, idField = "orderName", nameField = "orderName")
    @PutMapping("/start/{taskId}")
    public R<Void> startQuality(@PathVariable Long taskId) {
        return toAjax(qualityTaskService.startQuality(taskId));
    }

    /**
     * 完成质检
     */
    @SaCheckPermission("quality:task:complete")
    @Log(title = "完成质检", linkType = "quality", businessType = BusinessType.UPDATE, idField = "orderName", nameField = "orderName")
    @PutMapping("/complete")
    public R<Void> completeQuality(@RequestParam Long taskId,
                                   @RequestParam Integer qualityResult,
                                   @RequestParam(required = false) String remark) {
        return toAjax(qualityTaskService.completeQuality(taskId, qualityResult, remark));
    }

    /**
     * 暂停质检任务
     */
    @SaCheckPermission("quality:task:pause")
    @Log(title = "暂停质检任务", linkType = "quality", businessType = BusinessType.UPDATE, idField = "orderName", nameField = "orderName")
    @PutMapping("/pause/{taskId}")
    public R<Void> pauseTask(@PathVariable Long taskId, @RequestParam(required = false) String remark) {
        return toAjax(qualityTaskService.pauseTask(taskId, remark));
    }

    /**
     * 恢复质检任务
     */
    @SaCheckPermission("quality:task:resume")
    @Log(title = "恢复质检任务", linkType = "quality", businessType = BusinessType.UPDATE, idField = "orderName", nameField = "orderName")
    @PutMapping("/resume/{taskId}")
    public R<Void> resumeTask(@PathVariable Long taskId) {
        return toAjax(qualityTaskService.resumeTask(taskId));
    }


    /**
     * 修改质检时长
     */
    @MonitorMethod(bizType = BizTypeConstant.QUALITY+"Overdue", extractor = QualityDataExtractor.class)
    @Log(title = "提交质检响应时间", linkType = "quality", businessType = BusinessType.UPDATE, nameField = "name")
    @RepeatSubmit()
    @PostMapping("/submitDays/{id}/{days}")
    public R<ErpQualityTask> submitDays(@PathVariable("id") Long id, @PathVariable("days") Integer days) {
        return R.ok(qualityTaskService.submitDays(id,days));
    }

    /**
     * 校验任务单号是否唯一
     */
    @GetMapping("/checkTaskNoUnique")
    public R<Boolean> checkTaskNoUnique(@RequestParam String taskNo, @RequestParam(required = false) Long id) {
        return R.ok(qualityTaskService.checkTaskNoUnique(taskNo, id));
    }

    /**
     * 根据批次ID查询质检任务
     */
    @SaCheckPermission("quality:task:query")
    @GetMapping("/getByBatchId/{orderNo}")
    public R<List<ErpQualityTaskVo>> getByBatchId(@PathVariable Long orderNo) {
        List<ErpQualityTaskVo> list = qualityTaskService.getByBatchId(orderNo);
        return R.ok(list);
    }

    /**
     * 查询待质检任务数量
     */
    @SaCheckPermission("quality:task:query")
    @GetMapping("/getPendingTaskCount")
    public R<Integer> getPendingTaskCount(@RequestParam(required = false) Long assignUserId) {
        Integer count = qualityTaskService.getPendingTaskCount(assignUserId);
        return R.ok(count);
    }

    /**
     * 查询超时任务列表
     */
    @SaCheckPermission("quality:task:list")
    @GetMapping("/getTimeoutTasks")
    public R<List<ErpQualityTaskVo>> getTimeoutTasks() {
        List<ErpQualityTaskVo> list = qualityTaskService.getTimeoutTasks();
        return R.ok(list);
    }

    /**
     * 批量分配任务
     */
    @SaCheckPermission("quality:task:assign")
    @Log(title = "批量分配质检任务", businessType = BusinessType.UPDATE)
    @PutMapping("/batchAssign")
    public R<Void> batchAssignTasks(@RequestParam List<Long> taskIds,
                                    @RequestParam Long assignUserId,
                                    @RequestParam String assignUserName) {
        return toAjax(qualityTaskService.batchAssignTasks(taskIds, assignUserId, assignUserName));
    }

    /**
     * 更新任务优先级
     */
    @SaCheckPermission("quality:task:edit")
    @Log(title = "更新任务优先级", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePriority")
    public R<Void> updatePriority(@RequestParam Long taskId, @RequestParam Integer priority) {
        return toAjax(qualityTaskService.updatePriority(taskId, priority));
    }


    /**
     * 审核通过
     */
    @MonitorMethod(bizType =BizTypeConstant.QUALITY+"Overdue", extractor = QualityDataExtractor.class)
    @Log(title = "质检任务审批-通过", linkType = "quality", businessType = BusinessType.INSERT, idField = "taskNo", nameField = "taskNo")
    @PostMapping("/approve/{taskId}")
    public R<ErpQualityTask> approveTask(@PathVariable Long taskId) {
        try {
            ErpQualityTask task = qualityTaskService.approveTask(taskId);
            return R.ok("审核通过成功",task);
        } catch (Exception e) {
            return R.fail("审核通过失败: " + e.getMessage());
        }
    }

    /**
     * 审核拒绝
     */
    @MonitorMethod(bizType = BizTypeConstant.QUALITY+"Overdue", extractor = QualityDataExtractor.class)
    @Log(title = "质检任务审批-驳回", linkType = "quality", businessType = BusinessType.REJECT, idField = "taskNo", nameField = "taskNo")
    @PostMapping("/reject/{taskId}")
    public R<ErpQualityTask> rejectTask(@PathVariable Long taskId) {
        try {
            ErpQualityTask task = qualityTaskService.rejectTask(taskId);
            return R.ok("审核拒绝成功，已启动超期监控",task);
        } catch (Exception e) {
            return R.fail("审核拒绝失败: " + e.getMessage());
        }
    }
}
